#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string>

#define PATH "."
#define FIFO_FILE "fifo"

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

class Namepipe
{
public:
    Namepipe(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        _filename = _path + "/" + _name;

        umask(0);
        int n = mkfifo(_filename.c_str(), 0666);

        if (n < 0)
        {
            ERR_EXIT("mkfifo");
        }
        std::cout << "fifo created" << std::endl;
    }

    ~Namepipe()
    {
        int number = unlink(_filename.c_str());
        if (number == 0)
        {
          ERR_EXIT("unlink");
        }
        else
        {
            std::cout << "unlink fifo error" << std::endl;
        }
    }

private:
    std::string _path;
    std::string _filename;
    std::string _name;
};

class FileOperator
{

public:
    FileOperator(const std::string &path, const std::string &name)
        : _path(path), _name(name), _fd(-1)
    {
        _filename = _path + "/" + _name;
    }

    void OpenForRead()
    {
        _fd = open(_filename.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open fifo");
            return;
        }

        std::cout << "open fifo success" << std::endl;
    }

    void OpenForWrite()
    {
        _fd = open(_filename.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open fifo");
            return;
        }
        std::cout << "open fifo success" << std::endl;
    }

    void Read()
    {
        char buffer[256];

        while (1)
        {
            int n = read(_fd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "client say#:" << buffer << std::endl;
            }
            else if (n == 0)
            {
                std::cout << "client exit,me too" << std::endl;
                break;
            }
            else
            {
                std::cerr << "read fifo error" << std::endl;
                break;
            }
        }
    }

    void Write()
    {
        std::string message;
        int cnt = 1;
        pid_t id = getpid();
        while (1)
        {
            std::cout << "please enter#:";

            getline(std::cin, message);

            message += ", message number: " + std::to_string(cnt++) + ",pid: [" + std::to_string(id) + "]";

            write(_fd, message.c_str(), message.size());
        }
    }

    void Close()
    {
        if (_fd > 0)
        {
            close(_fd);
        }
    }
    
    ~FileOperator()
    {
    }

private:
    std::string _path;
    std::string _filename;
    std::string _name;
    int _fd;
};